<!--
 * @Description: zzb
 * @Version: 0.0.1
 * @Autor: zzb
 * @Date: 2023-02-22 11:44:10
 * @LastEditors: zzb
 * @LastEditTime: 2023-02-22 17:17:02
-->
 <!-- 菜单页代码  contextButton/index.vue -->
<template>
  <ul class="contextmenu" ref="contextmenu" v-show="visible">
    <li class="contextmenu__item" v-for="(item, index) in menuList" :key="index" @click="handleMenu(item)">
      {{ item.title }}
    </li>
  </ul>
</template>
 
<script>
export default {
  name: "ContextButton",
  props: {
    menuList: {
      typeof: Array,
      default: () => {
        return [
          { title: "菜单一", value: 0, command: "first" },
          { title: "菜单二", value: 1, command: "second" },
          { title: "菜单三", value: 2, command: "third" },
          { title: "菜单四", value: 3, command: "fourth" },
        ];
      },
    },
    visible: {
      typeof: Boolean,
      default: false,
    },
  },
  data() {
    return {};
  },
  mounted() {
    document.body.appendChild(this.$el);
  },
  watch: {
    visible(val) {
      if (val) {
        document.body.appendChild(this.$el);
      }
    },
  },
  methods: {
    init(row, column, e, container) {
      console.log("🚀 ~ file: index.vue:39 ~ init ~ e", e);
      e.preventDefault();

      let containerW = container.clientWidth;
      let containerH = container.clientHeight;
      // 设置菜单出现的位置
      // 具体显示位置根据自己需求进行调节
      let menu = this.$refs.contextmenu;
      let menuW = menu.clientWidth;
      let menuH = menu.clientHeight;

      let setX = e.clientX;
      let setY = e.clientY;
      console.log(setX, setY);
      if (e.clientX + menuW > containerW) {
        setX -= menuW;
      }
      if (e.clientY + menuH > containerH) {
        setY -= menuH;
      }

      menu.style.left = setX + "px";
      menu.style.top = setY + "px";

      document.body.addEventListener("click", this.foo); // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
    },
    foo() {
      console.log(111);
      this.$emit("update:visible", false);
    },
    handleMenu(item) {
      this.$emit("handleMenu", item);
    },
  },
  destroyed() {
    // if appendToBody is true, remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  },
};
</script>
 
<style scoped>
.contextmenu__item {
  display: block;
  line-height: 34px;
  text-align: center;
}
.contextmenu__item:not(:last-child) {
  border-bottom: 1px solid rgba(64, 158, 255, 0.2);
}
.contextmenu {
  position: absolute;
  background-color: #ecf5ff;
  width: 100px;
  /*height: 106px;*/
  font-size: 12px;
  color: #409eff;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid rgba(64, 158, 255, 0.2);
  white-space: nowrap;
  z-index: 1000;
}
.contextmenu__item:hover {
  cursor: pointer;
  background: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}
</style>